from django.shortcuts import render, redirect
from course import models
import hashlib
# Create your views here.

def index(request):

    return render(request, 'users/index.html')

def login(request):
    if request.method == 'GET':
        # 用户初次进入展示登录表单
        return render(request, 'users/login.html')
    elif request.method == 'POST':
        context = {
            'message': ''
        }
        username = request.POST.get('username')
        password = request.POST.get('password')
        # 查询数据库  验证账户名 密码
        user = models.User.objects.filter(name=username).first()
        if user:
            if user.password == password:
                context['message'] = '登录成功'
                request.session['is_login'] = True
                request.session['username'] = user.name
                request.session['userid'] = user.id
                return redirect('../course/')
            else:
                context['message'] = '密码不正确'
                return render(request, 'users/login.html', context=context)
        else:
            context['message'] = '未注册'
        return render(request, 'users/login.html', context=context)

def register(request):
    if request.method == 'GET':
        # 注册表单
        return render(request, 'users/register.html')
    elif request.method == 'POST':
        # 表单验证  写数据库
        username = request.POST.get('username')
        password = request.POST.get('password')
        email = request.POST.get('email')
        print(username)

        # 写数据库
        user = models.User.objects.filter(email=email).first()
        if user:
            return render(request, 'users/register.html', context={'message': '用户已注册'})
        try:
            user = models.User(name=username, password=password, email=email)
            user.save()
            print('保存成功')
            return render(request, 'users/register.html', {'message': '注册数据库保存成功， 继续登录'})
        except Exception as e:
            print('保存失败', e)
            return redirect('../users/register/')


def logout(request):
    """ 登出 """  # 清除此用户session对应的所有session
    request.session.flush()
    return redirect('/login/')